<template>
  <div class="admin-settings">
    <h1>{{ $t('message.adminSettings') }}</h1>
    
    <div class="settings-container">
      <div class="settings-tabs">
        <button 
          v-for="tab in tabs" 
          :key="tab.id"
          :class="['tab-button', { active: currentTab === tab.id }]"
          @click="currentTab = tab.id"
        >
          {{ $t(tab.title) }}
        </button>
      </div>
      
      <div class="settings-content">
        <!-- Platform Settings Tab -->
        <div v-if="currentTab === 'platform'" class="tab-content">
          <h2>{{ $t('message.platformSettings') }}</h2>
          
          <form @submit.prevent="savePlatformSettings" class="settings-form">
            <div class="form-group">
              <label for="platform-name">{{ $t('message.platformName') }}</label>
              <input 
                id="platform-name" 
                type="text" 
                v-model="platformSettings.name" 
                class="form-control"
              />
            </div>
            
            <div class="form-group">
              <label for="platform-description">{{ $t('message.platformDescription') }}</label>
              <textarea 
                id="platform-description" 
                v-model="platformSettings.description" 
                class="form-control"
                rows="4"
              ></textarea>
            </div>
            
            <div class="form-group">
              <label for="contact-email">{{ $t('message.contactEmail') }}</label>
              <input 
                id="contact-email" 
                type="email" 
                v-model="platformSettings.contactEmail" 
                class="form-control"
              />
            </div>
            
            <div class="form-group">
              <label>
                <input 
                  type="checkbox" 
                  v-model="platformSettings.maintenanceMode"
                />
                {{ $t('message.maintenanceMode') }}
              </label>
            </div>
            
            <button type="submit" class="btn btn-primary">
              {{ $t('message.saveChanges') }}
            </button>
          </form>
        </div>
        
        <!-- Youbi Settings Tab -->
        <div v-if="currentTab === 'youbi'" class="tab-content">
          <h2>{{ $t('message.youbiSettings') }}</h2>
          
          <form @submit.prevent="saveYoubiSettings" class="settings-form">
            <div class="form-group">
              <label for="min-deposit">{{ $t('message.minDepositAmount') }}</label>
              <input 
                id="min-deposit" 
                type="number" 
                v-model="youbiSettings.minDeposit" 
                class="form-control"
                min="0"
              />
            </div>
            
            <div class="form-group">
              <label for="max-withdrawal">{{ $t('message.maxDailyWithdrawal') }}</label>
              <input 
                id="max-withdrawal" 
                type="number" 
                v-model="youbiSettings.maxWithdrawal" 
                class="form-control"
                min="0"
              />
            </div>
            
            <div class="form-group">
              <label for="deposit-fee">{{ $t('message.depositFeePercent') }}</label>
              <input 
                id="deposit-fee" 
                type="number" 
                v-model="youbiSettings.depositFee" 
                class="form-control"
                min="0"
                max="100"
              />
            </div>
            
            <div class="form-group">
              <label for="transaction-fee">{{ $t('message.transactionFeePercent') }}</label>
              <input 
                id="transaction-fee" 
                type="number" 
                v-model="youbiSettings.transactionFee" 
                class="form-control"
                min="0"
                max="100"
              />
            </div>
            
            <button type="submit" class="btn btn-primary">
              {{ $t('message.saveChanges') }}
            </button>
          </form>
        </div>
        
        <!-- User Management Tab -->
        <div v-if="currentTab === 'users'" class="tab-content">
          <h2>{{ $t('message.userManagement') }}</h2>
          
          <div class="user-management-actions">
            <div class="form-group">
              <label for="user-search">{{ $t('message.searchUsers') }}</label>
              <input 
                id="user-search" 
                type="text" 
                v-model="userSearchQuery" 
                :placeholder="$t('message.searchByUsernameOrEmail')"
                class="form-control"
              />
            </div>
            
            <div class="users-list">
              <div 
                v-for="user in filteredUsers" 
                :key="user.userId" 
                class="user-item"
              >
                <div class="user-info">
                  <span class="username">{{ user.username }}</span>
                  <span class="email">{{ user.email }}</span>
                  <span class="role">{{ user.roleId }}</span>
                </div>
                <div class="user-actions">
                  <button 
                    class="btn btn-warning"
                    @click="toggleUserStatus(user)"
                  >
                    {{ user.status === 'ACTIVE' ? $t('message.deactivate') : $t('message.activate') }}
                  </button>
                  <button 
                    class="btn btn-danger"
                    @click="deleteUser(user)"
                  >
                    {{ $t('message.delete') }}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';

export default {
  name: 'AdminSettings',
  setup() {
    const currentTab = ref('platform');
    
    // Platform settings
    const platformSettings = ref({
      name: '',
      description: '',
      contactEmail: '',
      maintenanceMode: false
    });
    
    // Youbi settings
    const youbiSettings = ref({
      minDeposit: 0,
      maxWithdrawal: 0,
      depositFee: 0,
      transactionFee: 0
    });
    
    // Users
    const users = ref([]);
    
    const userSearchQuery = ref('');
    
    const tabs = [
      { id: 'platform', title: 'message.platformSettings' },
      { id: 'youbi', title: 'message.youbiSettings' },
      { id: 'users', title: 'message.userManagement' }
    ];
    
    // Load settings from API
    const loadSettings = async () => {
      try {
        // Load platform settings
        const platformResponse = await axios.get('/api/admin/settings/platform');
        platformSettings.value = {
          ...platformSettings.value,
          ...platformResponse.data
        };
        
        // Load youbi settings
        const youbiResponse = await axios.get('/api/admin/settings/youbi');
        youbiSettings.value = {
          ...youbiSettings.value,
          ...youbiResponse.data
        };
        
        // Load users
        const usersResponse = await axios.get('/api/admin/users');
        users.value = usersResponse.data || [];
      } catch (error) {
        console.error('Error loading settings:', error);
        // Fallback to mock data if API fails
        platformSettings.value = {
          name: 'YouKe Tutoring Platform',
          description: 'A comprehensive online tutoring platform',
          contactEmail: 'admin@youke.com',
          maintenanceMode: false
        };
        
        youbiSettings.value = {
          minDeposit: 10.0,
          maxWithdrawal: 10000.0,
          depositFee: 0.0,
          transactionFee: 0.0
        };
        
        users.value = [
          { userId: '1', username: 'admin', email: 'admin@youke.com', roleId: 'ADMIN', status: 'ACTIVE' },
          { userId: '2', username: 'teacher1', email: 'teacher1@youke.com', roleId: 'TEACHER', status: 'ACTIVE' },
          { userId: '3', username: 'parent1', email: 'parent1@youke.com', roleId: 'PARENT', status: 'ACTIVE' },
          { userId: '4', username: 'teacher2', email: 'teacher2@youke.com', roleId: 'TEACHER', status: 'INACTIVE' },
          { userId: '5', username: 'parent2', email: 'parent2@youke.com', roleId: 'PARENT', status: 'SUSPENDED' }
        ];
      }
    };
    
    const filteredUsers = computed(() => {
      if (!userSearchQuery.value) return users.value;
      
      const query = userSearchQuery.value.toLowerCase();
      return users.value.filter(user => 
        user.username.toLowerCase().includes(query) || 
        user.email.toLowerCase().includes(query)
      );
    });
    
    const savePlatformSettings = async () => {
      try {
        await axios.post('/api/admin/settings/platform', platformSettings.value);
        alert('Platform settings saved successfully!');
      } catch (error) {
        console.error('Error saving platform settings:', error);
        alert('Failed to save settings: ' + error.message);
      }
    };
    
    const saveYoubiSettings = async () => {
      try {
        await axios.post('/api/admin/settings/youbi', youbiSettings.value);
        alert('Youbi settings saved successfully!');
      } catch (error) {
        console.error('Error saving youbi settings:', error);
        alert('Failed to save settings: ' + error.message);
      }
    };
    
    const toggleUserStatus = async (user) => {
      try {
        const newStatus = user.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
        await axios.put(`/api/admin/users/${user.userId}/status`, {
          status: newStatus
        });
        
        // Update UI
        user.status = newStatus;
      } catch (error) {
        console.error('Error updating user status:', error);
        alert('Failed to update user status: ' + error.message);
      }
    };
    
    const deleteUser = async (user) => {
      if (confirm(`Are you sure you want to delete user ${user.username}?`)) {
        try {
          await axios.delete(`/api/admin/users/${user.userId}`);
          
          // Update UI
          const index = users.value.findIndex(u => u.userId === user.userId);
          if (index !== -1) {
            users.value.splice(index, 1);
          }
        } catch (error) {
          console.error('Error deleting user:', error);
          alert('Failed to delete user: ' + error.message);
        }
      }
    };
    
    onMounted(() => {
      loadSettings();
    });
    
    return {
      currentTab,
      platformSettings,
      youbiSettings,
      users,
      userSearchQuery,
      tabs,
      filteredUsers,
      savePlatformSettings,
      saveYoubiSettings,
      toggleUserStatus,
      deleteUser
    };
  }
};
</script>

<style scoped>
.admin-settings {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.admin-settings h1 {
  color: #2c3e50;
  margin-bottom: 1.5rem;
}

.settings-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.settings-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
}

.tab-button {
  padding: 1rem 1.5rem;
  border: none;
  background: transparent;
  cursor: pointer;
  font-size: 1rem;
  color: #7f8c8d;
  transition: all 0.3s ease;
}

.tab-button:hover {
  background-color: #e9ecef;
  color: #2c3e50;
}

.tab-button.active {
  background-color: #3498db;
  color: white;
  border-bottom: 3px solid #2980b9;
}

.settings-content {
  padding: 1.5rem;
}

.tab-content h2 {
  color: #2c3e50;
  margin-bottom: 1.5rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #eee;
}

.settings-form {
  max-width: 600px;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
  color: #2c3e50;
}

.form-control {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.form-control[type="checkbox"] {
  width: auto;
  margin-right: 0.5rem;
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-warning {
  background-color: #f39c12;
  color: white;
}

.btn-warning:hover {
  background-color: #d35400;
}

.btn-danger {
  background-color: #e74c3c;
  color: white;
}

.btn-danger:hover {
  background-color: #c0392b;
}

.user-management-actions {
  max-width: 800px;
}

.users-list {
  margin-top: 1.5rem;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.user-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.username {
  font-weight: 600;
  color: #2c3e50;
}

.email {
  color: #7f8c8d;
}

.role {
  padding: 0.25rem 0.5rem;
  background-color: #e1f0fa;
  color: #3498db;
  border-radius: 4px;
  font-size: 0.8rem;
}

.user-actions {
  display: flex;
  gap: 0.5rem;
}

@media (max-width: 768px) {
  .settings-container {
    margin: 0 1rem;
  }
  
  .settings-tabs {
    flex-direction: column;
  }
  
  .user-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.25rem;
  }
  
  .user-actions {
    margin-top: 0.5rem;
  }
}
</style>